/* 
 * This program is free software; you can redistribute it and/or modify 
 * it under the terms of the GNU General Public License as published by 
 * the Free Software Foundation; either version 3 of the License, or 
 * (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful, but 
 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY 
 * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 
 * for more details.
 * 
 * You should have received a copy of the GNU General Public License along 
 * with this program; if not, write to the Free Software Foundation, Inc., 
 * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
 */


#include "filtertext.h"

namespace Wishmaster
{
	FilterText::FilterText(const QString& name, const QString& regexp, bool cis) : Filter(name)
	{
		if(!regexp.isEmpty())
			setRegexp(regexp);
		setCaseInsensitive(cis);
	}

	FilterText::~FilterText()
	{
	}

	bool FilterText::check(PostPtr post)
	{
		if(m_regexp.indexIn(post->text()) >= 0)
			return true;
		if(m_regexp.indexIn(post->topic()) >= 0)
			return true;
		return false;
	}

	bool FilterText::checkText(const QString& text)
	{
		return m_regexp.indexIn(text) >= 0;
	}

	void FilterText::setRegexp(const QString& rx)
	{
		m_regexp.setPattern(rx);
	}

	QString FilterText::id()
	{
		return "filtertext";
	}
	
	QString FilterText::serialize()
	{
		QString opts;
		if(m_regexp.caseSensitivity() == Qt::CaseInsensitive)
			opts += 'i';
		return QString("filtertext@%1://%2:").arg(name()).arg(opts) + m_regexp.pattern();
	}

	bool FilterText::deserialize(const QString& s)
	{
		int index = s.indexOf(':');
		if(index < 0)
			return false;
		QString options = s.left(index);
		QString regexp = s.mid(index + 1);
		m_regexp.setPattern(regexp);
		if(options.contains('i'))
			m_regexp.setCaseSensitivity(Qt::CaseInsensitive);
		return true;
	}

	FilterPtr FilterText::clone(const QString& name)
	{
		return FilterPtr(new FilterText(name));
	}

	void FilterText::setCaseInsensitive(bool i)
	{
		if(i)
			m_regexp.setCaseSensitivity(Qt::CaseSensitive);
		else
			m_regexp.setCaseSensitivity(Qt::CaseInsensitive);
	}
	
	QString FilterText::regexp()
	{
		return m_regexp.pattern();
	}

	bool FilterText::caseInsensitive()
	{
		return (m_regexp.caseSensitivity() == Qt::CaseInsensitive);
	}
}

